import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
import java.io.*;
public class Enc_RSA{
    public static void main(String args[]) throws Exception{
        String s="Hello World!";
        // 获取公钥及参数e,n
        FileInputStream f= getFileInputStream();
        ObjectInputStream b= getObjectInputStream(f);
        RSAPublicKey  pbk=(RSAPublicKey)b.readObject( );
        BigInteger e= getPublicExponent(pbk);
        BigInteger n= getModulus(pbk);
        getPrintln("e= " + e);
        getPrintln("n= "+n);
        // 明文 m
        byte ptext[]=s.getBytes("UTF8");
        BigInteger m= getBigInteger(ptext);
        // 计算密文c,打印
        BigInteger c=m.modPow(e,n);
        getPrintln("c= "+c);
        // 保存密文
        String cs=c.toString( );
        BufferedWriter out=
                new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream("Enc_RSA.dat")));
        out.write(cs,0,cs.length( ));
        out.close( );

    }

    private static BigInteger getBigInteger(byte[] ptext) {
        return new BigInteger(ptext);
    }

    private static void getPrintln(String x) {
        System.out.println(x);
    }

    private static BigInteger getModulus(RSAPublicKey pbk) {
        return pbk.getModulus();
    }

    private static BigInteger getPublicExponent(RSAPublicKey pbk) {
        return pbk.getPublicExponent();
    }

    private static ObjectInputStream getObjectInputStream(FileInputStream f) throws IOException {
        return new ObjectInputStream(f);
    }

    private static FileInputStream getFileInputStream() throws FileNotFoundException {
        return new FileInputStream("Skey_RSA_pub.dat");
    }
}